package com.cipher;

public class CaesarExample {

    public static void main(String[] args) {
        String encryptedText = encrypt("life is full of uncertainties and challenges. no matter how difficult the path ahead, we should face it bravely and keep moving forward. only through perseverance and effort can we achieve true success and growth.", 6);
        System.out.println("加密后的文本: " + encryptedText);

        // 破解
        //System.out.println("暴力破解尝试:");
        //bruteForce(encryptedText);

        //  bruteForce("RD IJFW OJSSD");
        //  bruteForce("QTANSL DTZ NX XT JFXD.");

        //String decrypt = decrypt("RD IJFW OJSSD QTANSL DTZ NX XT JFXD. YMJWJFWJXTRFSD YMNSLX YT QTAJ FGTZY DTZ! IT DTZ PSTB N QTAJ NY BMJS DTZ IFDIWJFR FSI DTZ YMNSP ST TSJ NX BFYHMNSL? IT DTZPSTB N QTAJ YMJ BFD DTZW JDJX XUFWPQJ BMJS DTZ YJQQ F KZSSD XYTWD? IT DTZ PSTB YMFY N QTAJ YMJ XMFUJ TK DTZW JFWX?  IT DTZ PSTB N QTAJ YT BFYHM DTZ XQJJU? N HTZQI LT TS FSI TS. NFR YMJWJ BNYM DTZ, QTANSL DTZ.KWTR JIINJ", 5);
        //System.out.println(decrypt);
    }

    // 加密方法
    public static String encrypt(String text, int shift) {
        StringBuilder encryptedText = new StringBuilder();
        shift = shift % 26;  // 限制移位在 0 到 25 之间

        for (int i = 0; i < text.length(); i++) {
            char letter = text.charAt(i);

            // 如果是大写字母
            if (letter >= 'A' && letter <= 'Z') {
                encryptedText.append((char) ((letter - 'A' + shift) % 26 + 'A'));
            }
            // 如果是小写字母
            else if (letter >= 'a' && letter <= 'z') {
                encryptedText.append((char) ((letter - 'a' + shift) % 26 + 'a'));
            }
            // 保留非字母字符
            else {
                encryptedText.append(letter);
            }
        }
        return encryptedText.toString();
    }

    // 解密方法
    public static String decrypt(String text, int shift) {
        return encrypt(text, 26 - shift);  // 解密相当于用 26 - shift 进行加密
    }


    // 破解方法（尝试所有移位值）
    public static void bruteForce(String encryptedText) {
        for (int shift = 1; shift < 26; shift++) {
            String decryptedText = decrypt(encryptedText, shift);
            System.out.println("移位 " + shift + " : " + decryptedText);
        }
    }


}
